package com.lw.leetcode.binary.c;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 2234. 花园的最大总美丽值
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/15 16:12
 */
public class MaximumBeauty {

    public static void main(String[] args) {
        MaximumBeauty test = new MaximumBeauty();


        // 14
        int[] arr = {1,1,1,3};
        long newf = 7;
        int t = 6;
        int full = 12;
        int partial = 1;

        // 30
//        int[] arr = {2, 3, 4, 5};
//    long newf = 10;
//    int t = 5;
//    int full = 2;
//    int partial = 6;

        // 58
//        int[] arr = {1, 5, 5, 9, 15};
//        long newf = 36;
//        int t = 12;
//        int full = 9;
//        int partial = 2;

        // 47
//        int[] arr = {1, 1, 5, 6, 10, 10, 11, 12, 18, 19, 20};
//        long newf = 6;
//        int t = 20;
//        int full = 3;
//        int partial = 11;

        // 195
//        int[] arr = {1, 2, 5, 6, 9, 10, 11, 11, 12, 14, 15, 16, 17};
//        long newf = 80;
//        int t = 14;
//        int full = 15;
//        int partial = 1;

        long l = test.maximumBeauty(arr, newf, t, full, partial);
        System.out.println(l);
    }


    public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) {
        Arrays.sort(flowers);
        long length = flowers.length;
        if (flowers[0] >= target) {
            return length * full;
        }
        long[] arr = new long[(int) length];
        for (int i = 1; i < length; i++) {
            arr[i] = arr[i - 1] + (flowers[i] - flowers[i - 1]) * (long) i;
        }
        int binary = binary(flowers, target);
        long max = 0;
        for (int i = binary; i >= 0; i--) {
            long t = newFlowers + 1;
            int st = 0;
            int end = i;
            while (st < end) {
                int m = st + ((end - st + 1) >> 1);
                if (arr[m] < t) {
                    st = m;
                } else {
                    end = m - 1;
                }
            }
            long min = (newFlowers - arr[st]) / (st + 1) + flowers[st];
            if (i == 0 && min >= target) {
                max = Math.max((length - i) * full, max);
            }
            min = Math.min(min, target - 1L);
            max = Math.max((length - i - 1) * full + min * partial, max);
            int b = target - flowers[i];
            if (b > newFlowers) {
                break;
            }
            newFlowers -= b;
        }
        return max;
    }

    public int binary(int[] nums, long target) {
        int st = 0;
        int end = nums.length - 1;
        while (st < end) {
            int m = st + ((end - st + 1) >> 1);
            if (nums[m] < target) {
                st = m;
            } else {
                end = m - 1;
            }
        }
        return st;
    }

}
